/**
 * 
 */
package application;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import javax.swing.AbstractListModel;


/**
 * @author Nixon Duarte
 *
 */
public class FileStateAgent extends AbstractListModel {

	private static final long serialVersionUID = 2339826205033150908L;
	private static transient FileStateAgent fsw = null;
    
	private Map<File, DownloadState> hm = null;
	private transient File statesFile;

	public static FileStateAgent init( File statesFile ){
		if( statesFile.exists()){
			try {
				ObjectInputStream in = new ObjectInputStream( new FileInputStream(statesFile) );
				fsw = (FileStateAgent)in.readObject();
				fsw.setStatesFile( statesFile );
				in.close();
				return fsw;
			} catch (Exception e) { e.printStackTrace();}
		}
		fsw = new FileStateAgent( statesFile );
		return fsw;
	}

    private void setStatesFile(File statesFile2) {
    	this.statesFile = statesFile2;
	}

	public static FileStateAgent getInstance(){
    	return fsw;
    }
    
    /**
     * 
     * @param path
     */
    private FileStateAgent(File downloadStatesFile)
    {    	
    	hm = Collections.synchronizedMap( new HashMap<File, DownloadState>());
    	statesFile = downloadStatesFile;
    }
    
    public void  persistir() {
    	ObjectOutputStream out;
		try {
			out = new ObjectOutputStream(new FileOutputStream(statesFile));
	    	out.writeObject(this);
	    	out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
    
    public DownloadState getEstado(File f){
    	return hm.get(f);
    }

    public void borrarEstado(DownloadState ds){
    	hm.remove(ds.getLocalDownloadingFile());
		fireContentsChanged(this, 0, hm.size());
    	persistir();
    }
	
	public void setEstado( DownloadState ds ){
		hm.put(ds.getLocalDownloadingFile(), ds );
		fireContentsChanged(this, 0, hm.size());
		persistir();
	}

	@Override
	public Object getElementAt(int index) {
		synchronized( hm ){

			Set<Entry<File,DownloadState>> s = hm.entrySet();
			int i = 0;
			for (Entry<File,DownloadState> e : s ) {
				if( i == index ){
					return e.getValue();
				}
				i ++;
			}
			throw new IndexOutOfBoundsException();
		}
	}

	@Override
	public int getSize() {
		return hm.size();
	}	
}
